package com.logic.modular.game.player.bag.service;


import com.comment.exception.ServiceException;
import com.logic.comment.util.RedisUtils;
import com.comment.pojo.domain.bag.BagItem;
import com.comment.pojo.domain.logic.core.CoreProp;
import com.logic.modular.gameCore.cultivate.prop.CorePropServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 背包物品服务---货币服务
 */
@Slf4j
@Service
public class PlayerPropType1ServiceImpl {
    @Resource
    private BagItemServiceImpl bagItemService;
    @Resource
    private RedisUtils redisUtils;

    public BagItem viewCurrency(Long playerId, Long corePropId) {
        BagItem bagItem = bagItemService.list(playerId).stream().filter(item -> item.getCorePropId().equals(corePropId)).findFirst().orElse(null);
        if (bagItem == null) {
            throw new ServiceException(String.format("%s%d","背包内没有货币:", corePropId));
        }
        return bagItem;
    }


    /**
     * 尝试扣除货币
     *
     * @param playerId   玩家id
     * @param corePropId 货币id
     * @param num        使用数量(>0)
     * @return 是否成功
     */
    public boolean tryPay(Long playerId, Long corePropId, BigDecimal num) {
        CoreProp cache = CorePropServiceImpl.getCache(corePropId);
        if (!cache.getType().equals(1)) {
            log.error("非货币");
            return false;
        }
        BagItem bagItem = bagItemService.list(playerId).stream().filter(item -> item.getCorePropId().equals(corePropId)).findFirst().orElse(null);
        if (bagItem == null) {
            log.error("背包内没有货币:{}", corePropId);
            return false;
        }

        if (bagItem.num.compareTo(num) < 0) {
            log.error("背包内货币:{}不足{},当前：{}", corePropId, num.intValue(), bagItem.num.intValue());
            bagItem.giveUpHandlerPower();
            bagItem.checkCellStatus(CorePropServiceImpl.getCache(corePropId));
            bagItemService.updateById(bagItem);
            return false;
        }
        bagItemService.obtainBagItem(playerId, corePropId, num.negate());
        log.info("扣除货币成功");
        return true;
    }

    public void clearCopper(Long uid, Long corePropId) {
        bagItemService.clearProp(uid, corePropId);
    }
}
